/**
 *	CSCI 3033 Final Project
 *
 *	@author:  	Cody Hazelwood, Micah High
 *  @version:	1.0
 *	Due Date:	May 5, 2010
 *	Platform:	Android 2.1-update 1
 *				Android API version 7
 *	Comments:	This is the main application file for
 *              RecordaNote.  It displays the main
 *              view, and it takes care of creating
 *              the quick todo notes.
 *
 **/

package csci3033.RecordaNote;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
//import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class RecordaNote extends Activity{
	private String		filename = "RecordaNote.sod";	//Filename to store serialized Recording Objects
	private Button		btnNewToDo;						//Button to start a New To Do
	private Button		btnNewRecording;				//Button to start a New Recording
	private ListView	lstRecordingList;				//List View to list Recording Objects
	private ArrayList<Recording> recordings = new ArrayList<Recording>();
	
	private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
	private static final int RECORDING_REQUEST_CODE = 99999;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        // TODO Check for SD Card
        
        setContentView(R.layout.main);
        initControls();
        
        restoreRecordingsList();
		lstRecordingList.setAdapter(new RecordingAdapter(this, R.layout.row, recordings));
		registerForContextMenu(lstRecordingList);
        
        // Check to see if a recognition activity is present
    	PackageManager pm = getPackageManager();
    	List<ResolveInfo> activities = pm.queryIntentActivities(
    		new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
    	if (activities.size() != 0) {
    		btnNewToDo.setOnClickListener(new Button.OnClickListener() {
    			public void onClick (View v) {
    				startSpeechRecognition();       }});
    	} 
    	else {
    		btnNewToDo.setEnabled(false);
    		btnNewToDo.setText("Recognizer not present");
    	}
    	
    	// Sets up NewRecording button to allow it to be clicked
    	btnNewRecording.setOnClickListener(new View.OnClickListener() {
    		public void onClick(View v) {
    			goToRecordingScreenView();
    	}});
    }
    
    @Override
    public void onPause() {
    	saveApplicationData();
    	super.onPause();
    }
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    	super.onCreateContextMenu(menu, v, menuInfo);
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.recordinglistcontextmenu, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	//AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    	switch (item.getItemId()) {
    		case R.id.view:
    			//editNote(info.id);
    			return true;
    		case R.id.send:
    			//send something
    			return true;
    		case R.id.delete:
    			//deleteNote(info.id);
    			return true;
    		default:
    			return super.onContextItemSelected(item);
    	}
    }
    
    private void initControls() {
    	btnNewToDo = (Button) findViewById(R.id.btnNewToDo);
    	btnNewRecording = (Button) findViewById(R.id.btnNewRecording);
    	lstRecordingList = (ListView) findViewById(R.id.lstRecordingList);
    }
    
    /**
     * Start speech recognition activity
     */
    private void startSpeechRecognition() {
    	Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    	intent.putExtra(RecognizerIntent.ACTION_RECOGNIZE_SPEECH, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    	startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
    }
    
    private void goToRecordingScreenView() {
    	Intent i = new Intent(RecordaNote.this, RecordingScreen.class);
    	startActivity(i);
    	//startActivityForResult(i, RECORDING_REQUEST_CODE);
    }
    
    /**
     * Called when the Speech Recognition activity returns
     */
    protected void onActivityResult (int requestCode, int resultCode, Intent data) {
    	if (requestCode == RECORDING_REQUEST_CODE) {
    		if(resultCode == RESULT_OK){
    			//Creates a new recording with a name spoken by the user
	    		//Automatically marks recording as a ToDo
	    		recordings.add(new Recording(data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS).get(0), true, Calendar.getInstance()));
	    		lstRecordingList.setAdapter(new RecordingAdapter(this, R.layout.row, recordings));
    		}
    	}
    	
    	else if (requestCode == VOICE_RECOGNITION_REQUEST_CODE){
    		if (resultCode == RESULT_OK) {
    			//Creates a new recording with a name spoken by the user
        		//Automatically marks recording as a ToDo
        		recordings.add(new Recording(data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS).get(0), true, Calendar.getInstance()));
        		lstRecordingList.setAdapter(new RecordingAdapter(this, R.layout.row, recordings));
        	}
    		else {
    		Toast.makeText(getApplicationContext(), "Error with speech recognition.  Please try again.", 5).show();
    		}
    	}
    	
    	super.onActivityResult(requestCode, resultCode, data);
    }
    
    /**
     * Save the list of Recording objects (using serialization)
     */
    private void saveApplicationData() {
    	File					file      = new File (getExternalFilesDir(null), filename);
    	FileOutputStream 		outFile   = null;
    	ObjectOutputStream 		outObject = null;
    	try {
    		outFile   = new FileOutputStream(file);
    		outObject = new ObjectOutputStream(outFile);
    		
    		if (recordings.size() > 0) {
    			outObject.writeInt(recordings.size());
    			for (int i=0; i < recordings.size(); i++){
    				outObject.writeObject(recordings.get(i));
    			}
    		}
    		
    		outObject.close();
    		outFile.close();
    	}
    	catch (IOException exception) {
    		Toast.makeText(getApplicationContext(), "Error!\n" + exception.getMessage() + "I'm a save error.", 25).show();
    	}
    }
    
    /**
     * Restores the saved list of Recording objects (recordings or todo's)
     */
    private void restoreRecordingsList() {
    	File					file     = new File (getExternalFilesDir(null), filename);
    	FileInputStream 		inFile   = null;
    	ObjectInputStream 		inObject = null;
    	
    	//Read in the file
    	try {
    		if(file != null) {
    			inFile   = new FileInputStream(file);
    			inObject = new ObjectInputStream(inFile);
    			
    			int size = inObject.readInt();
    			for (int i=0; i < size; i++) {
    				recordings.add((Recording)inObject.readObject());
    			}
    			
    			inObject.close();
    			inFile.close();
    		}
    	}
    	catch (IOException exception) {
    		Toast.makeText(getApplicationContext(), "Error!\n" + exception.getMessage(), 5).show();
    	}
    	catch (ClassNotFoundException exception) {
    		Toast.makeText(getApplicationContext(), "Class not found!\n" + exception.getMessage(), 5).show();
    	}
    }
    
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
	}
    
}